use redb::{Database, ReadableDatabase, ReadableTable, TableDefinition};
use af_util::MinecraftProfile;
const MC_PROFILES_TABLE: TableDefinition<'_, &str, MinecraftProfile> =
    TableDefinition::new("mcprofiles");

pub fn save_profile(p: MinecraftProfile) -> anyhow::Result<()> {
    let db = Database::open("redb.db")?;
    let tx = db.begin_write()?;
    tx.open_table(MC_PROFILES_TABLE)?
        .insert(&*p.name.clone(), p)?;
    tx.commit()?;
    Ok(())
}

pub fn init_db() -> anyhow::Result<()> {
    let db = Database::create("redb.db")?;
    let tx = db.begin_write()?;
    tx.open_table(MC_PROFILES_TABLE)?;
    tx.commit()?;
    Ok(())
}

pub fn get_all_profiles() -> anyhow::Result<Vec<MinecraftProfile>> {
    let db = Database::open("redb.db")?;
    let tx = db.begin_read()?;
    let table = tx.open_table(MC_PROFILES_TABLE)?;
    let mut profiles: Vec<MinecraftProfile> = Vec::new();
    table.iter()?.for_each(|i| {
        if let Ok((_k, v)) = i {
            profiles.push(v.value());
        }
    });
    Ok(profiles)
}

pub fn get_profile_by_name(name: &str) -> anyhow::Result<Option<MinecraftProfile>> {
    let db = Database::open("redb.db")?;
    let tx = db.begin_read()?;
    let table = tx.open_table(MC_PROFILES_TABLE)?;
    let profile = table.get(name)?.map(|v| v.value());
    Ok(profile)
}
